package com.ip.common.utils;

import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2017/09/19 09:59
 */
public class Md5Utils {

    /**
     *	32位MD5加密
     * @param msg 明文
     * @return 32位密文
     */
    public static String encryption(String msg) {
//        if (StrUtils.isEmpty(msg)) {
//            return null;
//        }
//        if (msg == null) {
//            return null;
//        }
        String re_md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(msg.getBytes());
            byte[] b = md.digest();
            int i;
            StringBuilder buf = new StringBuilder();
            for (byte value : b) {
                i = value;
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            re_md5 = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }


    public static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String hex(byte[] array) {
        StringBuilder sb = new StringBuilder();
        for (byte b : array) {
            sb.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString();
    }

    public static String md5Hex (String message) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return hex (md.digest(message.getBytes("CP1252")));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMD5Str(String sMsg) {
        byte[] msg = sMsg.getBytes();
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(msg);
        } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
        }
        byte[] b = messageDigest.digest();
        return new String(Base64.encodeBase64(b));
    }

    public static String getMD5Str1(String sMsg) {
        byte[] msg = sMsg.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(msg);
        } catch (NoSuchAlgorithmException ignored) {
        }
        byte[] b = messageDigest.digest();
        return new String(Base64.encodeBase64(b));
    }

    public static String getMD5Str2(String sMsg) {

        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(sMsg.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuilder md5StrBuff = new StringBuilder();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString();
    }

    /**
     * Method MD5Encode
     * Description 说明：
     */
    public static String MD5Encode(String origin) {
        String resultString = null;

        try {
            resultString = origin;

            MessageDigest md = MessageDigest.getInstance("MD5");

            resultString = byteArrayToHexString(md.digest(resultString.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultString;
    }

    /**
     * Method byteToHexString
     * Description 说明：
     *
     * @param b 说明：
     * @return 返回值说明：
     */
    private static String byteToHexString(byte b) {
        int n = b;

        if (n < 0) {
            n += 256;
        }

        int d1 = n >>> 4;
        int d2 = n % 16;

        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * Field hexDigits
     * Description
     */
    private final static String[] hexDigits = {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
    };

    /**
     * Method byteArrayToHexString
     * Description 说明：
     *
     * @param b 说明：
     * @return 返回值说明：
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();

        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }

        return resultSb.toString();
    }

    public static String digest(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] buffer = md.digest();

            StringBuilder sb = new StringBuilder(buffer.length * 3);
            for (byte b : buffer) {
                sb.append(Character.forDigit((b & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(b & 0x0f, 16));
            }
            return sb.toString();
        }catch (Exception e){
            RuntimeException e1 = new RuntimeException("md5 异常");
            e1.addSuppressed(e);
            throw e1;
        }
    }

    /**
     * Method MD5Encode add salt
     * Description 说明：
     */
    public static String MD5Encode(String origin, String salt) {
        String resultString = null;

        try {
            resultString = origin;

            MessageDigest md = MessageDigest.getInstance("MD5");

            resultString = byteArrayToHexString(md.digest(mergePasswordAndSalt(resultString, salt).getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultString;
    }

    private static String mergePasswordAndSalt(String password, String salt) {
        if (password == null) {
            password = "";
        }

        if ((salt == null) || "".equals(salt)) {
            return password;
        } else {
            return password + "{" + salt + "}";
        }
    }

    public static String createSalt() {
        String all = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        char[] c = all.toCharArray();
        Random r = new Random();
        String s = "";
        while (s.length()<6) {
            int index = r.nextInt(c.length);
            char c1 = c[index];
            s += c1;
        }
        return s;
    }

    public static String defaultPassWord() {
        return MD5Encode("cqmall.com666");
    }

    public static void main(String[] args) {
        String s = MD5Encode("123456");
        String salt = createSalt();
        System.out.println(salt);
        String admin = MD5Encode(s.toUpperCase(), "qwert");
        System.out.println(s+"-------"+ admin);
    }
}
